/**
 * 泛娱区块链 - 关于我们
 * @author: zaric
 * @creation time: 2018-12-17
 */


'use strict';
import React from 'react';
import {View, Text, StyleSheet, TouchableOpacity, Image, TextInput} from 'react-native';
import NavigationBar from '../../component/navigation/NavigationBar';
import Container from '../../component/common/Container';
import Button from '../../component/common/Button';
import Images from '../../asset';
import ServicesApi from '../../config/ServicesApi';
import Theme from '../../config/themes/Theme';
import WrapContainer from "../../component/common/WrapContainer";
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view';
import ImagePickerManager from '../../config/manager/ImagePickerManager'
import ImageView from '../../component/common/ImageView';
import LargePicture from "../../component/common/LargePicture";

class FeedBack extends React.Component {

    constructor(props) {
        super(props);
        this.state = {imageData: [{type: 'add', source: Images.img_photo_add}],};
        this.inputData = {
            feedContact: '',
            feedContent: '',
            feedDetails: ''
        }
    }

    componentDidMount() {

    }
    //反馈意见
    requestFeedBack = async () => {
        const {imageData} = this.state;
        let imgArr = [];
        imageData.map((item,i) => {
            if (item.type !== 'add'){
                imgArr.push(item.source)
            }
        });
        let imgStr = imgArr.join(',');
        let params = {
            fb_title: this.inputData['feedContent'],
            fb_content: this.inputData['feedDetails'],
            fb_user_contact: this.inputData['feedContact'],
            fb_user: global.secretKey,
            fb_imgs: imgStr,
        };
        const result = await Services.post(ServicesApi.FEED_BACK, params);
        if (result.code === StatusCode.SUCCESS_CODE) {
            ToastManager.show('提交成功');
            RouterHelper.goBack();
        }else {
            ToastManager.show(result.dec || 'error')
        }
    };

    _onPressFeedBack = () => {
        let params = {
            title: '温馨提示',
            detail: '',
            actions: [
                {
                    title: '确定', onPress: () => {
                    }
                }
            ]
        };
        if (!this.inputData['feedContent']) {
            params['detail'] = '请输入反馈建议';
            AlertManager.show(params)
        } else if (!this.inputData['feedDetails']) {
            params['detail'] = '请输入反馈详情';
            AlertManager.show(params)
        } else if (!this.inputData['feedContact']) {
            params['detail'] = '请输入联系方式';
            AlertManager.show(params)
        } else {
            this.requestFeedBack()
        }
    };

    //点击图片选择
    _onPressImage = async (item, index) => {
        const {imageData} = this.state;
        if (imageData.length === 4) { //+1，把加号图片也要算上
            ToastManager.show('最多上传三张');
            return;
        }
        if (item.type === 'add') {
            const result = await ImagePickerManager.showMultipleImagePicker({imageCount: 1});
            // console.log(`===========${result.code}`);
            if (result.code === StatusCode.SUCCESS_CODE) {
                const upRes = await Services.uploadQiNiu(result.data);
                if (upRes.code === StatusCode.SUCCESS_CODE) {
                    let newData = imageData.slice();
                    const index = imageData.length - 1;
                    newData.splice(index, 0, {
                        type: `data${Moment().format('x')}`,
                        source: upRes.data[0].key,
                    });
                    this.setState({imageData: newData});
                }
            }
        }
    };

    _onChangeText = (key, text) => {
        this.inputData[key] = text
    };

    _onPressDel = (id, index) => {
        let newData = this.state.imageData.slice();
        let tempCount = this.state.imageCount;
        newData.splice(index, 1);
        this.setState({imageData: newData, imageCount: tempCount + 1});
    };

    renderImageItem = ({item, index, width}) => {
        if (item.type === 'add') {
            return (
                <TouchableOpacity key={`add_touch`} onPress={() => this._onPressImage(item, index)}>
                    <Image
                        key={`add_image`}
                        style={[styles.image, {width, height: width}]}
                        source={item.source}
                    />
                </TouchableOpacity>
            )
        }
        return (
            <View>
                <LargePicture
                    imageStyle={[styles.image, {width, height: width}]}
                    source={{uri: item.source}}
                />

                <TouchableOpacity
                    style={styles.delView}
                    onPress={() => this._onPressDel(item.type, index)}
                >
                    <ImageView
                        source={Images.icon_del}
                        style={styles.iconStyle}
                    />
                </TouchableOpacity>
            </View>
        )
    };

    render() {
        const {imageData} = this.state
        return (
            <View style={styles.container}>
                <NavigationBar
                    title={'意见反馈'}
                />
                <KeyboardAwareScrollView>
                    <View>
                        <TextInput
                            style={styles.title}
                            placeholder={'请输入您的建议'}
                            onChangeText={(text) => this._onChangeText('feedContent', text)}
                        />
                        <TextInput
                            multiline={true}
                            style={styles.content}
                            placeholder={'请对您的建议进行详细描述'}
                            onChangeText={(text) => this._onChangeText('feedDetails', text)}
                        />
                        <TextInput
                            style={styles.contact}
                            placeholder={'邮箱/手机号'}
                            onChangeText={(text) => this._onChangeText('feedContact', text)} 
                            keyboardType={'numeric'}
                        />
                        <WrapContainer
                            style={styles.wrapContainer}
                            data={imageData}
                            keyExtractor={(item, index) => `photo${index}`}
                            numColumns={4}
                            itemColumnMargin={5}
                            itemRowMargin={10}
                            renderItem={this.renderImageItem}
                        />
                        <Button
                            style={styles.button}
                            title={'提交建议'}
                            onPress={this._onPressFeedBack}
                        />
                    </View>
                </KeyboardAwareScrollView>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff'
    },
    title: {
        width: Theme.screenWidth - 30,
        paddingVertical: 10,
        marginHorizontal: 15,
        borderWidth: Theme.minPixel,
        borderColor: '#dbdbdb',
        borderRadius: 3,
        fontSize: FontSize(16),
        color: '#333',
        marginTop: 20,
        paddingHorizontal: 5,
    },
    content: {
        width: Theme.screenWidth - 30,
        height: 121,
        marginHorizontal: 15,
        borderWidth: Theme.minPixel,
        borderColor: '#dbdbdb',
        borderRadius: 3,
        fontSize: FontSize(13),
        color: '#333',
        marginTop: 15,
        paddingHorizontal: 5,
        textAlign: 'left',
        textAlignVertical: 'top',
    },
    contact: {
        width: Theme.screenWidth - 30,
        paddingVertical: 10,
        marginHorizontal: 15,
        borderWidth: Theme.minPixel,
        borderColor: '#dbdbdb',
        borderRadius: 3,
        fontSize: FontSize(16),
        color: '#333',
        marginTop: 15,
        paddingHorizontal: 5,
    },
    wrapContainer: {
        marginTop: 15,
        marginHorizontal: 15,
    },
    image: {
        // width: 70,
        // height: 70,
    },
    button: {
        marginTop: 25,
        marginHorizontal: 30,
        backgroundColor: Theme.themeColor,
        color: '#fff'
    },
    delView: {
        position: 'absolute',
        top: 5,
        right: 5,
    },
    iconStyle: {
        width: 18,
        height: 17,
    },
});

export default FeedBack